;;; heap
(define (adjust* heap i j)
  (let ((vi (vector-ref heap i))
        (vj (vector-ref heap j)))
    (if (> vi vj)
      (begin
        (vector-set! heap i vj)
        (vector-set! heap j vi)))))

(define (make-heap size)
  (let ((heap (make-vector (+ size 1) #f)))
    (vector-set! heap 0 0)
    heap))

(define (heap-size heap)
  (vector-ref heap 0))

(define (heap-top heap)
  (vector-ref heap 1))

(define (heap-push! heap value)
  (let ((s (+ (heap-size heap) 1)))
    (vector-set! heap 0 s)
    (vector-set! heap s value)
    (do ((i s (quotient i 2))
         (p (quotient s 2) (quotient p 2)))
      ((not (and (> i 1) (adjust* heap p i)))))))

(define (heap-pop! heap)
  (let ((s (heap-size heap)))
    (define (go i)
      (let ((l (+ i i))
            (r (+ i i 1)))
        (cond
          ((>= l s))
          ((or (>= r s) (<= (vector-ref heap l) (vector-ref heap r)))
           (if (adjust* heap i l) (go l)))
          (else
           (if (adjust* heap i r) (go r))))))
    (vector-set! heap 0 (- s 1))
    (vector-set! heap 1 (vector-ref heap s))
    (go 1)))

;;; heap-test
; (define (heap-test!)
;   (let* ((n (read))
;          (h (make-heap n)))
;     (do ((i 0 (+ 1 i)))
;       ((= i n))
;       (let ((op (read)))
;         (cond
;           ((> op 0)
;            (heap-push! h (read)))
;           ((< op 0)
;            (heap-pop! h)))
;         (format #t "~a~%" (heap-top h))))
;     (do ()
;       ((= 0 (heap-size h)))
;       (format #t "~a~%" (heap-top h))
;       (heap-pop! h))))

(define (iterate n f x)
  (define (go n x acc)
    (if (zero? n)
      acc
      (go (- n 1) (f x) (cons x acc))))
  (reverse (go n x '())))

(define (gao n k a b c r)
  (let ((elem (iterate k (lambda (x)
                           (remainder (+ (* x b) c) r)) a))
        (heap (make-heap (+ k k 1)))
        (hash (make-hash-table k)))

    (define (go l acc)
      (if (null? l)
        (cons (heap-top heap) acc)
        (let* ((k (car l))
               (v (hash-ref hash k 0))
               (t (heap-top heap)))
          (heap-pop! heap)
          (hash-set! hash k (- v 1))
          (if (= v 1)
            (heap-push! heap k))
          (go (cdr l) (cons t acc)))))

    (for-each (lambda (x)
                (hash-set! hash x (+ (hash-ref hash x 0) 1))) elem)
    (do ((i 0 (+ i 1)))
      ((> i k))
      (if (not (hash-ref hash i))
        (heap-push! heap i)))
    (let ((vec (list->vector (reverse (go elem '()))))
          (off (remainder (- n k 1) (+ k 1))))
      (vector-ref vec off))))

(define (main)
  (let ((re (read)))
    (do ((ri 1 (+ ri 1)))
      ((> ri re))
      (let* ((n (read)) (k (read)) (a (read)) (b (read)) (c (read)) (r (read)))
        (format #t "Case #~a: ~a~%" ri (gao n k a b c r))))))

(main)
